import { useEffect, useState } from 'react';
import { useSelector } from 'react-redux';
import { Button, Checkbox, NavBar, Popup, Input } from '@nutui/nutui-react-taro';
import { ITouchEvent, Text, View, Image, Button as TaroButton, Input as TaroInput } from '@tarojs/components';
import { ArrowLeft } from '@nutui/icons-react-taro';
import { getUserCodeWX } from './pure';
import { IUserLogin } from '@/types/user';
import { setToken, setUser } from '@/utils/user';
import Taro from '@tarojs/taro';
import request from '@/utils/request';
import './index.less';
import { domain2 } from '@/constant';
import { uploadFileByForm } from '@/tools/upload';

const goPrivacyPolicy = (event: ITouchEvent) => {
  event.stopPropagation();
  Taro.navigateTo({ url: '/pages/clause-privacy-policy/index' });
};

export default function Index() {
  const barHeight = useSelector((state: any) => state.system.barHeight);
  const [loggedPhone, setLoggedPhone] = useState<string>('');
  const [isRead, setIsRead] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [phoneCode, setPhoneCode] = useState<string>(''); // 存储获取到的手机号凭证
  const [showProfilePopup, setShowProfilePopup] = useState<boolean>(false);
  const [avatarUrl, setAvatarUrl] = useState<string>('https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0');
  const [nickname, setNickname] = useState<string>('');

  /**
   * 获取用户的手机号，可能有也可能还没注册
   */
  const getRegistedPhone = async () => {
    const code = await getUserCodeWX();
    const phone = await request.get<string>('/user/phone/by-login-code', {
      code,
    });
    setLoggedPhone(phone || '');
  };

  /**
   * 进入页面时获取用户在系统中的手机号
   */
  useEffect(() => {
    getRegistedPhone();
  }, []);

  /**
   * 登录后把user存入redux
   */
  const afterLogin = (user: IUserLogin) => {
    if (user?.user?.id) {
      setUser(user.user);
    }
    setToken(user.accessToken as string);
    Taro.navigateBack();
  };

  /**
   * 校验是否阅读隐私政策
   */
  const beforeLogin = () => {
    if (isRead) return true;
    Taro.showToast({
      title: '请阅读并同意隐私政策',
      icon: 'none',
    });
    return false;
  };

  /**
   * 直接调用微信登录流程
   */
  const loginWithWechat = () => {
    if (!beforeLogin()) return;
    setLoading(true);
    
    try {
      // 获取登录code
      const code = getUserCodeWX().then(code => {
        // 普通登录
        request.post<IUserLogin>('/user/login', {
          code,
          nickName: nickname || `用户${Math.floor(Math.random() * 10000)}`, // 使用默认昵称
          avatarUrl: avatarUrl
        }).then(user => {
          afterLogin(user);
        }).catch(error => {
          console.error('登录失败', error);
          Taro.showToast({
            title: '登录失败，请重试',
            icon: 'none'
          });
          setLoading(false);
        });
      }).catch(error => {
        console.error('获取code失败', error);
        Taro.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        });
        setLoading(false);
      });
    } catch (error) {
      console.error('登录失败', error);
      Taro.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
      setLoading(false);
    }
  };

  /**
   * 处理手机号获取回调
   */
  const handleGetPhoneNumber = async (e) => {
    console.log('获取手机号回调', e.detail);
    
    if (!beforeLogin()) return;
    
    if (e.detail.errMsg !== "getPhoneNumber:ok") {
      Taro.showToast({
        title: '获取手机号失败，请重试',
        icon: 'none'
      });
      return;
    }
    
    // 保存手机号凭证
    setPhoneCode(e.detail.code);
    console.log('已保存手机号凭证', e.detail.code);
    
    // 使用Toast提示用户
    Taro.showToast({
      title: '已获取手机号，请继续完善资料',
      icon: 'none',
      duration: 1000
    });
    
    // 延迟一下再弹窗，避免被Toast覆盖
    setTimeout(() => {
      // 显示自定义弹窗
      setShowProfilePopup(true);
      console.log('打开了弹窗');
    }, 500);
  };
  
  /**
   * 处理选择头像回调
   */
  const handleChooseAvatar = (e) => {
    const { avatarUrl } = e.detail;
    
    // 如果是临时文件，上传到OSS
    Taro.showLoading({ title: '上传头像中...' });
    
    // 使用uploadFileByForm上传头像
    uploadFileByForm('/oss/upload', avatarUrl, { type: 'file' })
      .then(res => {
        if (res && res.code === 200 && res.data && res.data.url) {
          setAvatarUrl(res.data.url);
          console.log('头像上传成功:', res.data.url);
        } else {
          console.error('头像上传返回格式错误:', res);
          // 上传失败时仍使用临时路径
          setAvatarUrl(avatarUrl);
        }
      })
      .catch(err => {
        console.error('头像上传失败:', err);
        // 上传失败时仍使用临时路径
        setAvatarUrl(avatarUrl);
      })
      .finally(() => {
        Taro.hideLoading();
      });
  };
  
  /**
   * 处理昵称输入
   */
  const handleNicknameChange = (e) => {
    setNickname(e.detail.value);
  };
  
  /**
   * 提交用户资料
   */
  const submitUserProfile = async () => {
    if (!phoneCode) {
      Taro.showToast({
        title: '请先获取手机号',
        icon: 'none'
      });
      return;
    }
    
    if (!avatarUrl) {
      Taro.showToast({
        title: '请选择头像',
        icon: 'none'
      });
      return;
    }
    
    setLoading(true);
    setShowProfilePopup(false);
    
    try {
      // 获取登录code
      const code = await getUserCodeWX();
      
      // 微信一键登录
      const user = await request.post<IUserLogin>('/user/wechat-login', {
        code,
        phoneCode: phoneCode, // 使用已获取的手机号凭证
        nickName: nickname || `用户${Math.floor(Math.random() * 10000)}`, // 使用输入的昵称或默认昵称
        avatarUrl: avatarUrl // 使用选择的头像
      });
      
      afterLogin(user);
    } catch (error) {
      console.error('登录失败', error);
      Taro.showToast({
        title: '登录失败，请重试',
        icon: 'none'
      });
    } finally {
      setLoading(false);
    }
  };

  return (
    <View className="login">
      <View style={{ height: `${barHeight}px`, width: '100%' }}></View>
      <NavBar
        back={<ArrowLeft size={18} />}
        onBackClick={() =>
          Taro.redirectTo({ url: '/pages/index/index' })
        }></NavBar>
      <View className="title">
        <Image className="login-title" src={`${domain2}/logo.png`}  />
        {/* <View className="title-text-1">多多帮</View> */}
        <Image className="title-text-1" src={`${domain2}/ddb.png`}  />
        <View className="title-text-2">
          一键服务，便捷生活！
        </View>
      </View>
      
      <View className="footer">
        {loggedPhone ? (
          // 如果已经登录了，则直接登录
          <Button 
            shape="square" 
            type="primary" 
            loading={loading} 
            onClick={loginWithWechat}
            disabled={loading}
          >
            手机号快捷登录
          </Button>
        ) : (
          <TaroButton 
            openType="getPhoneNumber" 
            onGetPhoneNumber={handleGetPhoneNumber}
            className="wx-login-button"
            disabled={loading}
          >
            <View>手机号快捷登录</View>
          </TaroButton>
        )}
      </View>
      
      <View className="clause">
        <Checkbox
          checked={isRead}
          onChange={(val) => setIsRead(val)}
          label={
            <>
              <Text>已阅读并同意</Text>
              <Text className="clause-link" onClick={goPrivacyPolicy}>
                《隐私政策》
              </Text>
            </>
          }
        />
      </View>
      
      {/* 使用Popup代替Dialog，采用微信官方的头像和昵称获取方式 */}
      <Popup
        visible={showProfilePopup}
        style={{ padding: '30px 40px', width: '70vw', maxWidth: '320px' }}
        position="center"
        round
        closeable={false}
      >
        <View className="profile-popup">
          <View className="popup-title">完善个人资料</View>
          <View className="popup-content">请选择头像并输入昵称</View>
          
          <View className="avatar-section">
            <TaroButton 
              openType="chooseAvatar" 
              onChooseAvatar={handleChooseAvatar}
              className="avatar-wrapper"
            >
              <Image className="avatar" src={avatarUrl} />
            </TaroButton>
          </View>
          
          <View className="nickname-section">
            <TaroInput
              type="nickname"
              className="nickname-input"
              placeholder="请输入昵称"
              onInput={handleNicknameChange}
              value={nickname}
            />
          </View>
          
          <Button 
            type="primary" 
            onClick={submitUserProfile}
            style={{ marginTop: '20px' }}
          >
            确认提交
          </Button>
        </View>
      </Popup>
    </View>
  );
}
